
rm(list=setdiff(ls(), c("prepTex", "%!in%", "es_openq", "pl_openq", "es_sum", "pl_sum" , "run_start", "run_start_total")))

#2) Study 2: United Kingdom  ####   

list_exp <- readRDS("./data/GB_exp1.rds")

gb <- readRDS("./data/GB_exp2.rds")

ri <- readRDS("./data/GB_respondent.rds") %>% 
  select(id, egotropic, sociotropic, fair, equal, income_improve, income_worsen) %>% 
  mutate(egotropic = ifelse(egotropic %in% c("Agree", "Strongly agree"), 1, 0),
         sociotropic = ifelse(sociotropic %in% c("Agree", "Strongly agree"), 1, 0),
         fair = ifelse(fair %in% c("Agree", "Strongly agree"), 1, 0),
         equal = ifelse(equal %in% c("Agree", "Strongly agree"), 1, 0))

mean(gb$rating)
prop.table(table(gb$rating>4))

# 2.1) List Experiments ####

dplyr::left_join(list_exp %>% 
                   filter(treatment %!in% "Treatment 2"),
                 ri %>% select(id, egotropic),
                 by = "id") %>% 
  list::combinedListDirect(count ~ treatment + round,
                           data = ., 
                           treat = "treatment", direct = "egotropic") -> leout1

dplyr::left_join(list_exp %>% 
                   filter(treatment %!in% "Treatment 1"),
                 ri %>% select(id, sociotropic),
                 by = "id") %>% 
  list::combinedListDirect(count ~ treatment + round,
                           data = ., 
                           treat = "treatment", direct = "sociotropic") -> leout2

gbm1_list <- lm(count ~ treatment + round, list_exp)

gbm2_list <- lm(count ~ treatment * round, list_exp)

# 2.1.1) Table K1 ####

texreg::screenreg(list(prepTex(gbm1_list, data = list_exp), prepTex(gbm2_list, data = list_exp)))

texreg::texreg(list(prepTex(gbm1_list, data = list_exp), prepTex(gbm2_list, data = list_exp)), 
               file = "./tables/TableK1.tex",
               custom.model.names = c("Main effects", "Interactions"),
               custom.coef.names = c(NA, "Egotropic", "Equality",
                                     "Round 2",
                                     "Egotropic $\\times$ Round 2",
                                     "Equality $\\times$ Round 2"),
               float = "htb",
               caption = "List experiment: Egotropic and equality considerations",
               caption.above = T,
               label = "tab:TableK1", 
               custom.note = "\\parbox{0.6\\linewidth}{%stars. Entries are unstandardized coefficients from a linear regression model. Standard errors in parentheses are clustered on individuals.}",
               use.packages = F)


# 2.2) Main model ####

gbm1r <- lm(rating ~ ind + soc + partner_size + trade_volume + year, gb)
gbm1c <- lm(choice ~ ind + soc + partner_size + trade_volume + year, gb)

texreg::screenreg(list(prepTex(gbm1r, data = gb), prepTex(gbm1c, data = gb)))

# 2.2.1) Table 4 ####

texreg::texreg(list(prepTex(gbm1r, data = gb), prepTex(gbm1c, data = gb)),
               file = "./tables/Table4.tex",
               custom.model.names = c("Rating", "Choice"),
               custom.coef.map = list("indmedium" = "Medium gains",
                                      "indlarge" = "Large gains",
                                      "socsame" = "Average citizen same",
                                      "socmore" = "Average citizen more",
                                      "partner_sizesmall economy" = "Size of partner (Small)",
                                      "trade_volumelittle" = "Trade volume (Little)",
                                      "year2028" = "Year of Implementation (2028)",
                                      "(Intercept)" = NA),
               float = "htb",
               caption = "Relative societal gains and PTA support",
               caption.above = T,
               label = "tab:table4", 
               custom.note = "\\parbox{0.6\\linewidth}{%stars. Entries are unstandardized coefficients from a linear regression model. Standard errors in parentheses are clustered on respondents. Rating is captured on a seven-point scale. Choice is a dummy and we assume linear probabilities.}",
               use.packages = F)

# 2.2.1) Table I1 ####

gbm2r <- lm(rating ~ ind * soc + partner_size + trade_volume + year, gb)
gbm2c <- lm(choice ~ ind * soc + partner_size + trade_volume + year, gb)

texreg::screenreg(list(prepTex(gbm2r, data = gb), prepTex(gbm2c, data = gb)))

texreg::texreg(list(prepTex(gbm2r, data = gb), prepTex(gbm2c, data = gb)),
               file = "./tables/TableI1.tex",
               custom.model.names = c("Rating", "Choice"),
               custom.coef.map = list("indmedium" = "Medium gains",
                                      "indlarge" = "Large gains",
                                      "socsame" = "Average citizen same",
                                      "socmore" = "Average citizen more",
                                      "partner_sizesmall economy" = "Size of partner (Small)",
                                      "trade_volumelittle" = "Trade volume (Little)",
                                      "year2028" = "Year of Implementation (2028)",
                                      "indmedium:socsame" = "Medium gains $\\times$ Average citizen same",
                                      "indlarge:socsame" = "Large gains $\\times$ Average citizen same",
                                      "indmedium:socmore" = "Medium gains $\\times$ Average citizen more",
                                      "indlarge:socmore" = "Large gains $\\times$ Average citizen more",
                                      "(Intercept)" = NA),
               float = "htb",
               caption = "Conjoint results including interactions",
               caption.above = T,
               label = "tab:tableI1", 
               custom.note = "\\parbox{0.6\\linewidth}{%stars. Entries are unstandardized coefficients from a linear regression model. Standard errors in parentheses are clustered on respondents. Rating is captured on a seven-point scale. Choice is a dummy and we assume linear probabilities.}",
               use.packages = F)

# 2.3) Remove respondents with inconsistent behaviour ####

gb <- dplyr::left_join(gb, 
                       dplyr::left_join(gb %>% 
                                          select(id, side, round, rating) %>% 
                                          pivot_wider(names_from = side, names_prefix = "rating_", values_from = rating),
                                        gb %>% 
                                          select(id, side, round, choice) %>% 
                                          pivot_wider(names_from = side, names_prefix = "choice_",values_from = choice),
                                        by = c("id", "round")) %>% 
                         mutate(keep = ifelse((rating_A >= rating_B) & (choice_A > choice_B), 1, 
                                              ifelse((rating_B >= rating_A) & (choice_B > choice_A), 1, 0))) %>% 
                         select(id, round, keep),
                       by = c("id", "round"))

prop.table(table(gb$keep))

# 2.3.1) Table J1 ####

gbm1rkeep <- lm(rating ~ ind + soc + partner_size + trade_volume + year, gb, subset = keep == 1)
gbm1ckeep <- lm(choice ~ ind + soc + partner_size + trade_volume + year, gb, subset = keep == 1)

texreg::screenreg(list(prepTex(gbm1r, data = gb), prepTex(gbm1rkeep, data = gb %>% filter(keep==1)),prepTex(gbm1c, data = gb), prepTex(gbm1ckeep, data = gb %>% filter(keep==1))))

texreg::texreg(list(prepTex(gbm1r, data = gb), prepTex(gbm1rkeep, data = gb %>% filter(keep==1)),prepTex(gbm1c, data = gb), prepTex(gbm1ckeep, data = gb %>% filter(keep==1))),
               file = "./tables/TableJ1.tex",
               custom.model.names = c("Rating", "Rating w/o Inc.", "Choice", "Choice w/o Inc."),
               custom.coef.map = list("indmedium" = "Medium gains",
                                      "indlarge" = "Large gains",
                                      "socsame" = "Average citizen same",
                                      "socmore" = "Average citizen more",
                                      "partner_sizesmall economy" = "Size of partner (Small)",
                                      "trade_volumelittle" = "Trade volume (Little)",
                                      "year2028" = "Year of Implementation (2028)",
                                      "(Intercept)" = NA),
               float = "htb",
               scalebox = 0.85,
               caption = "Conjoint results for both dependent variables and without inconsistent responses",
               caption.above = T,
               label = "tab:tableJ1", 
               custom.note = "\\parbox{\\linewidth}{%stars. Entries are unstandardized coefficients from a linear regression model. Standard errors in parentheses are clustered on respondents. Rating is captured on a seven-point scale. Choice is a dummy and we assume linear probabilities.}",
               use.packages = F)

#2.4) Round effects ####

#2.4.1) Figure J1 ####

gb %>% 
  group_by(round) %>% 
  do(broom::tidy(lm(cbind(rating, choice) ~ ind + soc + partner_size + trade_volume + year, data = .))) %>% 
  filter(term %!in% c("(Intercept)")) %>% 
  mutate(term = factor(term,
                       levels = c("indmedium", "indlarge", "socsame", "socmore",
                                  "partner_sizesmall economy", "trade_volumelittle", "year2028"),
                       labels = c("Medium gains", "Large gains", "Average citizen same", "Average citizen more",
                                  "Small\npartner", "small trade\nvolume", "Implementation\nby 2028")),
         response = factor(response,
                           labels = c("Choice", "Rating"))) %>% 
  filter(grepl("gains", term) | grepl("citizen", term)) %>% 
  ggplot(., aes(x = forcats::fct_rev(round), y = estimate, 
                ymin = estimate - 1.96*std.error, ymax = estimate + 1.96*std.error)) +
  geom_hline(yintercept = 0, lty = "dotted") + 
  geom_pointrange(position = position_dodge(width = 1)) +
  coord_flip() +
  facet_grid(term~response, scales = "free_x") +
  labs(y = "Coefficient", x = "Round") + 
  theme_minimal()  +
  scale_y_continuous(minor_breaks = NULL)

ggsave(filename = "./figures/FigureJ1.pdf",
       width = 20, height = 18, units = "cm")


#2.5) Descriptive plot of battery ###########

# Figure 2 ####

readRDS("./data/GB_respondent.rds") %>% 
  labelled::remove_labels() %>% 
  select("sociotropic", "fair","equal", "egotropic") %>% 
  ggstats::gglikert(., variable_labels = c(egotropic = "I only care about the benefits I get from trade agreements, disregarding those of others.",
                                           sociotropic = "A trade agreement should not only benefit citizens of our country but also the partner country.",
                                           fair = "Ensuring a fair distribution of gains should be a priority in any trade agreement.",
                                           equal = "Nobody should gain or lose more than others from a trade agreement.")) +
  theme(legend.text = element_text(size = 10),
        axis.text = element_text(size = 10))

ggsave(filename = "./figures/Figure2.pdf", 
       width = 25, height = 12, units = "cm")

#2.6 Descriptives GB ##########

#quotas GB
quotas_gb <- readxl::read_xlsx("./data/quotas_es_pl_gb.xlsx", sheet = 3)

xtable::xtable(quotas_gb, 
               type = "latex", 
               label = "tab:TableH1", 
               digits = c(0,0,0,0,0,2), 
               align = c("c", "l", "l", "c", "c", "c"), 
               caption = "Representativeness of the British sample") %>%
  print(., file = "./tables/TableH1.tex",
        include.rownames = F, type = "latex", floating	= T, 
        table.placement	= "htb",
        caption.placement = "top")

#battery
gb_resp <- readRDS("./data/GB_respondent.rds") %>%
  mutate(Egotropic = ifelse(egotropic %in% c("Agree", "Strongly agree"), 1, 0),
         Sociotropic = ifelse(sociotropic %in% c("Agree", "Strongly agree"), 1, 0),
         Fair = ifelse(fair %in% c("Agree", "Strongly agree"), 1, 0),
         Equal = ifelse(equal %in% c("Agree", "Strongly agree"), 1, 0),
         Income_improve = ifelse(income_improve %in% c("Slightly improve", "Improve a lot"), 1, 0),
         Income_worsen = ifelse(income_worsen %in% c("Slightly worsen", "Worsen a lot"), 1, 0)) %>%
  select(Egotropic, Sociotropic, Fair, Equal, Income_improve, Income_worsen) %>%
  psych::describe(.) %>%
  select(n, Mean = mean, SD = sd, Min = min, Max = max) 

#list exp
list_resp <- list_exp %>%
  select(id,round,count) %>%
  group_by(id) %>%
  #  summarize(Count = mean(count)) %>%
  psych::describe(.) %>%
  select(n, Mean = mean, SD = sd, Min = min, Max = max)


#conjoint
conj_gb <- gb %>%
  select(partner_size, trade_volume, year, id, ind, soc, choice, rating) %>%
  group_by(id) %>%
  psych::describe(.) %>%
  select(n, Mean = mean, SD = sd, Min = min, Max = max)

#gb descriptives

conj_gb %>%
  rbind(.,list_resp) %>%
  rbind(.,gb_resp) %>%
  filter(rownames(.) %!in% c("id", "id1", "treatment*","round*")) %>%
  mutate(Variable = c("Size of partner", "Trade volume", "Year of Implementation", 
                      "Individual gains", "Average citizen gains", "Choice", "Rating", 
                      "Count", "Egotropic","Sociotropic","Fair","Equal",
                      "Income improves","Income worsens"), 
         "Survey item" = c("Conjoint","Conjoint","Conjoint","Conjoint","Conjoint","Conjoint","Conjoint",
                           "List experiment",
                           "Direct question","Direct question","Direct question","Direct question","Direct question","Direct question")) %>%
  select("Survey item", Variable, everything())%>%
  xtable::xtable(.,
                 digits = c(0, 0, 0, 0, 2, 2, 0, 0),
                 align = c("l", "l", "l" ,"c", "c", "c", "c", "c"),
                 caption = "Descriptive statistics United Kingdom") %>% 
  print(., file = "./tables/TableH2.tex",
        label = "tab:TableH2",
        include.rownames = F, type = "latex", floating	= T, 
        table.placement	= "htb",
        caption.placement = "top")
